package controllers

import (
	"doctor/models"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type DoctorController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *DoctorController) Add() {
	name := c.GetString("name")
	phone := c.GetString("phone")
	hosp := c.GetString("hosp")
	department := c.GetString("department")
	title := c.GetString("title")
	times := time.Now()
	cate := c.GetString("cate")
	fen, _ := c.GetInt("fen")
	doctor := models.Doctor{
		Name:       name,
		Phone:      phone,
		Hosp:       hosp,
		Department: department,
		Title:      title,
		Times:      times,
		Cate:       cate,
		Fen:        fen,
	}
	err := models.DB.Create(&doctor).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *DoctorController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	doctors, total, err := models.ListDoctor(page, pageSize)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["doctors"] = doctors
		pageData["total"] = total
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "分页查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *DoctorController) Del() {
	id, _ := c.GetInt("id")
	doctor := models.Doctor{Id: id}
	err := models.DB.Delete(&doctor).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *DoctorController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	phone := c.GetString("phone")
	hosp := c.GetString("hosp")
	department := c.GetString("department")
	title := c.GetString("title")
	times := time.Now()
	cate := c.GetString("cate")
	fen, _ := c.GetInt("fen")
	doctor := models.Doctor{
		Id:         id,
		Name:       name,
		Phone:      phone,
		Hosp:       hosp,
		Department: department,
		Title:      title,
		Times:      times,
		Cate:       cate,
		Fen:        fen,
	}
	err := models.DB.Updates(&doctor).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
